<!--
 * @Author: Junxu
 * @Date: 2024-07-18 13:55:29
 * @LastEditors: Junxu
 * @LastEditTime: 2024-07-31 17:29:26
 * @Description: 维修报告详情H5
-->
<template>
  <div>
    <div style="height: 0; overflow: hidden">
      <report-detail-pdf :info="info"></report-detail-pdf>
    </div>
    <!-- <div v-if="imgDataUrl">
      <img :src="imgDataUrl" style="width: 100%" alt="" />
      <div style="padding: 30rpx 0">
        --------------------------分割线-------------------------
      </div>
    </div> -->
    <!-- <page-meta> -->
    <div class="report-edit">
      <div class="report-edit-content" id="reportEdit">
        <div class="top-card">
          <div class="top-card-title">电梯故障维修报告</div>
          <div class="top-card-content">
            <div>尊敬的客户：</div>
            <div>
              您好！以下是关于本次电梯故障的维修报告，我们力求以最简单明了的方式，让您了解故障的全貌及我们的处理过程。
            </div>
          </div>
          <div class="top-card-pic">
            <image
              src="./static/report_pic.png"
              mode="widthFix"
              style="width: 88px"
            ></image>
          </div>
        </div>
        <div class="report-card">
          <div class="report-card-title">
            <div class="text">电梯基本信息</div>
          </div>
          <div class="row">
            <div class="title">电梯名称</div>
            <div class="content">
              {{ info.buildingName }} {{ info.elevatorAddress }}
            </div>
          </div>
          <div class="row">
            <div class="title">电梯品牌</div>
            <div class="content">{{ info.brandName }}</div>
          </div>
          <div class="row">
            <div class="title">额定载重</div>
            <div class="content">{{ info.supportingPower }}kg</div>
          </div>
          <div class="row">
            <div class="title">额定速度</div>
            <div class="content">{{ info.speed }}m/s</div>
          </div>
        </div>
        <div class="report-card">
          <div class="report-card-title">
            <div class="text">故障现象与原因</div>
          </div>
          <div class="row">
            <div class="title">报障时间</div>
            <div class="content">{{ info.planCreateTime }}</div>
          </div>
          <div class="part-card" v-for="(item, i) in info.reasonList" :key="i">
            <div class="part-card-title">
              <div class="serial-num">{{ i + 1 }}</div>
              <div class="content">
                {{ item.partsNames | replaceAmpersand }}
                <span v-if="item.floorStandNames">({{ item.floorStandNames.replaceAll(',','>') }})</span>
              </div>
            </div>
            <div class="part-card-content">
              <div class="row">
                <div class="title">现象</div>
                <div class="content">{{ item.mfDesc }}</div>
              </div>
              <div class="row">
                <div class="title">原因</div>
                <div class="content">{{ item.faultReason }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="report-card" id="projectCard">
          <div class="report-card-title">
            <div class="text">故障处理方案</div>
          </div>
          <div class="part-card" v-for="(item, i) in info.projectList" :key="i">
            <div class="part-card-title">
              <div class="serial-num">{{ i + 1 }}</div>
              <div class="content">
                {{ item.partsNames | replaceAmpersand }}
                <span v-if="item.floorStandNames">({{ item.floorStandNames.replaceAll(',','>') }})</span>
              </div>
            </div>
            <div class="part-card-content">
              <div class="row">
                <div class="title">方案</div>
                <div class="content">
                  {{ item.faultDesc }}
                </div>
              </div>
              <div class="row">
                <div class="title">配件更换</div>
                <div class="content">
                  {{ item.partsOpeText }}
                </div>
              </div>
              <div class="column" style="padding-top: 8px">
                <div class="title">处理前图片</div>
                <div class="content">
                  <template v-for="(img, j) in item.mfImgUrl">
                    <img
                      v-if="img.type === 'image'"
                      :key="j"
                      class="report-img"
                      mode="widthFix"
                      crossorigin="anonymous"
                      :src="`${img.url}?33${Date.now()}_${i}_${j}`"
                      alt=""
                    />
                  </template>
                </div>
              </div>
              <div class="column">
                <div class="title">处理后图片</div>
                <div class="content">
                  <template v-for="(img, j) in item.faultImg">
                    <img
                      v-if="img.type === 'image'"
                      :key="j"
                      class="report-img"
                      mode="widthFix"
                      crossorigin="anonymous"
                      :src="`${img.url}?22${Date.now() + j}`"
                      alt=""
                    />
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="report-card">
          <div class="report-card-title">
            <div class="text">维保人员</div>
          </div>
          <div class="row">
            <div class="title">姓名</div>
            <div class="content">{{ info.planUserName }}</div>
          </div>
          <div class="row">
            <div class="title">报告日期</div>
            <div class="content">{{ info.createTime }}</div>
          </div>
        </div>
        <div class="report-edit-info">
          感谢贵方选择使用我司提供的产品和服务，我们将持续提供专业、高效的服务，确保您的电梯运行无忧。
        </div>
      </div>
      <div class="report-edit-footer" v-if="false">
        <div class="btn-box">
          <div class="btn" @click="onSubmit">生成报告</div>
        </div>
      </div>
      <div class="report-edit-footer" v-if="isError">
        <div class="btn-box">
          <div class="btn" @click="onEditReport">返回重新生成报告</div>
        </div>
      </div>
      <div class="report-edit-footer" v-if="isCheckReport">
        <div class="btn-box">
          <div class="btn" @click="onCheckReport">查看报告</div>
        </div>
      </div>
    </div>
    <!-- </page-meta> -->
  </div>
</template>
<script>
import { mapActions } from 'vuex';
import { hanleToken } from '@/utils/utils.js';
import reportDetailPdf from './components/report-detail-pdf.vue';
import { getReportDetail, addOrUpdateReport } from '@/apis/repair.js';
import { toJpeg } from 'html-to-image';
import jsPDF from 'jspdf';
const webWX = require('@/utils/jweixinSDK.js');
export default {
	name: 'ReportDetailH5',
	components: {
		reportDetailPdf,
	},
	filters: {
		replaceAmpersand(value) {
			if (!value) return '';
			return value.replace(/&amp;&amp;/g, '>');
		},
	},
	data() {
		return {
			showMsg: true,
			imgDataUrl: '',
			partList: [
				{
					value: 1,
					label: '无需更换',
				},
				{
					value: 2,
					label: '建议更换',
				},
				{
					value: 3,
					label: '已更换',
				},
			],
			info: {
				id: null,
				createUser: null,
				createDept: null,
				createTime: null,
				updateUser: null,
				updateTime: null,
				status: null,
				isDeleted: null,
				tenantId: null,
				planId: null,
				elevatorId: null,
				buildingId: null,
				elevatorAddress: null,
				buildingName: null,
				brandName: null,
				supportingPower: null,
				speed: null,
				sendStatus: null,
				reportData: [],
				reportFile: null,
				reportImg: null,
				planUserName: null,
				planCreateTime: null,
				planFinishTime: null,
				workOrderType: null,
				reportUserName: null,
				reportUserRole: null,
				reasonList: [],
				projectList: [],
			},
			timer: null,
			reportId: null, // 报告id
			isError: false,
			isCheckReport: false,
		};
	},
	async onLoad(e) {
		const { id, refresh_token } = e;
		if (refresh_token) {
			hanleToken('set', 'refresh_token', refresh_token);
			await this.handleRreshToken();
		}
		this.reportId = id;
		await this.getDetail();
	},
	beforeDestroy() {
		clearInterval(this.timer);
		this.timer = null;
	},
	methods: {
		...mapActions('user', ['handleRreshToken']),
		async getDetail() {
			uni.showLoading({
				title: '加载中',
			});
			try {
				const res = await getReportDetail({ reportId: this.reportId });
				console.log(res, 'res');
				if (res && res.code == 200 && res.data) {
					let reasonList = [];
					let projectList = [];
					if (res.data.reportData) {
						if (!Array.isArray(res.data.reportData)) {
							res.data.reportData = JSON.parse(res.data.reportData);
						}
						console.log(res.data.reportData, 'res.data.reportData');
						res.data.reportData.forEach((item) => {
							// item.mfImgUrl.forEach((v) => {
							//   v.url = v.url + `?${Date.now()}`;
							// });
							// item.faultImg.forEach((v) => {
							//   v.url = v.url + `?${Date.now()}`;
							// });
							// item.partsNames = item.partsNames.replace(new RegExp('&','g'),"&");
							reasonList.push({
								mfDesc: item.mfDesc,
								partsNames: item.partsNames,
								partsIds: item.partsIds,
								faultReason: item.faultReason,
								floorStandNames:item.floorStandNames,
							});
							projectList.push({
								faultDesc: item.faultDesc,
								faultImg: item.faultImg,
								mfImgUrl: item.mfImgUrl,
								partsNames: item.partsNames,
								partsIds: item.partsIds,
								partsOpe: item.partsOpe || 1,
								floorStandNames:item.floorStandNames,
								partsOpeText: this.partList.find(
									(v) => v.value == item.partsOpe
								).label,
							});
						});
					}
					console.log(res.data.reportData, 'res.data.reportData');
					res.data.reasonList = reasonList;
					res.data.projectList = projectList;
					this.info = res.data;
					this.onSubmit();
				}
				uni.hideLoading();
			} catch (error) {
				uni.hideLoading();
				console.log(error);
			}
		},
		onGenerateImageAndPDF() {
			Promise.all([this.handleCreateImage(), this.handleCreatePDF()])
				.then((res) => {
					console.log(res, 'res-all');
					this.updateReport(res);
				})
				.catch((err) => {
					this.isError = true;
					uni.hideLoading();
					uni.showToast({
						title: '生成图片PDF失败',
						icon: 'none',
					});
					console.log(err, '生成图片PDF失败');
				});
		},
		async createImage(node) {
			let isSafari = false;
			const info = wx.getSystemInfoSync();
			if (info.platform === 'ios') {
				isSafari = true;
				console.log('This is running on iOS.');
			} else {
				isSafari = false;
				// 这是在 Android 平台上
				console.log('This is running on Android.');
			}
			let dataUrl = '';
			let i = 0;
			let maxAttempts;
			maxAttempts = 5;
			let cycle = [];
			let repeat = true;
			if (isSafari) {
				maxAttempts = 6;
			} else {
				maxAttempts = 1;
			}
			while (repeat && i < maxAttempts) {
				dataUrl = await toJpeg(node, {
					fetchRequestInit: {
						cache: 'no-cache',
					},
					skipAutoScale: true,
					includeQueryParams: true,

					// pixelRatio: isSafari ? 1 : 2,
					pixelRatio: 2,
					quality: 1,
				});
				i += 1;
				cycle[i] = dataUrl.length;

				if (dataUrl.length > cycle[i - (isSafari ? 5 : 1)]) repeat = false;
			}
			console.log('safari:' + isSafari + '_repeat_need_' + i);
			return dataUrl;
		},
		handleCreateImage() {
			return new Promise(async (resolve, reject) => {
				// uni.showLoading({
				//   title: "生成图片中...",
				//   icon: "none",
				// });
				let dom = document.querySelector('#reportEdit');
				// // 设置元素的高度
				console.log(dom, 'dom-reportEdit');
				console.log(window.devicePixelRatio * 2, '增加清晰度');
				dom.style.width = 375 + 'px';
    
				const imgDataUrl = await this.createImage(dom);
				dom.style.width = 'auto';
				// this.imgDataUrl = imgDataUrl;
				// uni.hideLoading();
				// return;
				if (!imgDataUrl && imgDataUrl.length < 20) {
					uni.showToast({
						title: '生成失败，请减少上传的图片后重试！',
						icon: 'none',
					});
					reject(new Error('上传图片失败'));
				}
				try {
					const res = await this.http.uni_upload(imgDataUrl);
					console.log(res, 'res');
					this.imgDataUrl = res.data.link;
					if (res.code == 200) {
						resolve(res.data.link);
					} else {
						reject(new Error('上传图片失败'));
					}
				} catch (error) {
					reject(error);
				}
			});
		},
		handleCreatePDF() {
			return new Promise(async (resolve, reject) => {
				let dom = document.querySelector('#pdfPic');
				// const imgDataUrl = await toJpeg(dom, {
				//   skipAutoScale: true,
				//   pixelRatio: 2,
				//   quality: 1,
				// });
				const imgDataUrl = await this.createImage(dom);
				let width = 595;
				// 获取canvas转化后的宽度
				const canvasWidth = dom.offsetWidth;

				// 获取canvas转化后的高度
				const canvasHeight = dom.offsetHeight;

				// 高度转化为PDF的高度
				const height = (width / canvasWidth) * canvasHeight;
				const pdf = new jsPDF({
					orientation: 'p',
					unit: 'pt',
					format: [width, height], // 设置宽度为标准 A4，高度为足够大的值
				});
				console.log(height, 'height');
				// 添加图片到 PDF
				pdf.addImage(imgDataUrl, 'JPEG', 0, 0, width, height);
				let file = pdf.output('datauristring');
				if (!file && file.length < 20) {
					uni.showToast({
						title: '生成失败，请减少上传的图片后重试！',
						icon: 'none',
					});
					reject(new Error('上传PDF失败'));
				}
				// 保存 PDF
				// pdf.save("电梯故障维修报告_" + Date.now());
				try {
					const res = await this.http.uni_upload(file);
					console.log(res, 'res');
					if (res.code == 200) {
						resolve(res.data.link);
					} else {
						reject(new Error('上传PDF失败'));
					}
				} catch (error) {
					reject(error);
				}
			});
		},
		showSubmitMsg() {
			return new Promise((resolve, reject) => {
				uni.showModal({
					title: '维修报告生成提醒',
					content: '是否确认报告内容无误？生成后报告内容将无法更改，请谨慎操作',
					cancelText: '暂不生成',
					cancelColor: '#999999',
					confirmColor: '#0091ff',
					confirmText: '确认生成',
					success: function (res) {
						if (res.confirm) {
							resolve(true);
						} else {
							console.log('用户点击取消');
							uni.showModal({
								title: '维修报告发送提醒',
								content:
                  '检测到尚未发送维修报告，请确认报告无误后立即发送，否则系统将在10分钟后自动发送。',
								cancelText: '取消',
								cancelColor: '#999999',
								confirmColor: '#0091ff',
								confirmText: '确认发送',
								success: function (res2) {
									if (res2.confirm) {
										console.log('用户点击确定');
										resolve(true);
									} else {
										resolve(false);
										console.log('用户点击取消');
									}
								},
							});
						}
					},
					fail: function (err) {
						reject(err || new Error('User canceled the operation.'));
					},
				});
			});
		},
		async updateReport(data) {
			try {
				const param = {
					id: this.reportId,
					reportFile: data[1],
					reportImg: data[0],
				};
				const res = await addOrUpdateReport(param);
				if (res && res.code == 200 && res.data) {
					uni.hideLoading();
					uni.showToast({
						title: '报告生成成功',
						icon: 'success',
					});
					this.isError = false;
					setTimeout(() => {
						try {
							this.onCheckReport();
						} catch (error) {
							this.isCheckReport = true;
						}
					}, 300);
				}
			} catch (error) {
				this.isError = true;
				uni.hideLoading();
				uni.showToast({
					title: 'updateReport失败',
					icon: 'error',
				});
				console.log(error, 'updateReport');
			}
		},
		async onSubmit() {
			this.$nextTick(() => {
				uni.showLoading({
					title: '生成报告中请不要退出！',
					mask: true,
				});
				this.isError = false;
				this.timer = setInterval(() => {
					console.log(document.readyState, 'document.readyState');
					if (document.readyState === 'complete') {
						clearInterval(this.timer);
						this.timer = null;
						this.onGenerateImageAndPDF();
					}
				}, 1000);
			});
			// webWX.miniProgram.redirectTo({
			//   url: "/subpages/repair/reportShare?id=" + this.reportId,
			// });
			// let dom = document.querySelector("#reportEdit");
			// const resp = await domtoimage.toPng(dom, { quality: 2 });
			// this.imgDataUrl = resp;
			// const flag = await this.showSubmitMsg();
			// console.log(flag, "flag");
			// this.onGenerateImageAndPDF();
			// this.handleCreateImage();
			// this.handleCreatePDF();
		},
		onEditReport() {
			webWX.miniProgram.redirectTo({
				url: '/subpages/repair/reportEdit?reportId=' + this.reportId,
			});
		},
		onCheckReport() {
			webWX.miniProgram.redirectTo({
				url: '/subpages/repair/reportShare?id=' + this.reportId,
			});
		},
	},
};
</script>

<style lang="scss" scoped>
// @font-face {
//     font-family: '思源黑体 Regular';
//     src: url('https://erised-fresh.oss-cn-shenzhen.aliyuncs.com/592800/1722408210269_ww0akfjk.otf');

// }
.title {
  margin-bottom: 0px;
}
.report-edit {
  // width: 375px;
  // min-width: 375px;
  // max-width: 375px;
  div {
    box-sizing: border-box;
    font-size: 14px;
    font-family: '思源黑体 Regular', Helvetica, 'Microsoft YaHei', Arial, sans-serif;
  }
  .report-edit-msg-box {
    height: 56px;
    width: 100%;
  }

  &-msg {
    width: 100%;
    height: 56px;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 3;
    display: flex;
    align-items: center;
    // padding: 20px;
    padding: 0 10px;
    background: #fffadf;

    .content {
      word-break: break-all;
      flex: 1;
      width: 0;
      padding: 0 10px;
      color: #ff7505;
      font-size: 13px;
      line-height: 18px;
    }

    .close {
      //   width: 32px;
      //   height: 32px;
      margin-left: 15px;
    }
  }

  &-content {
    padding: 10px;
    background-color: #e2f3ff;

    .top-card {
      background-color: #fff;
      padding: 20px;
      border-radius: 4px;
      position: relative;
      margin-bottom: 8px;

      &::before,
      &::after {
        content: "";
        position: absolute;
        width: 10px; // 半圆的直径
        height: 10px;
        border-radius: 50%; // 创建圆形
        background-color: #e2f3ff;
      }

      &::before {
        left: -5px;
        top: 55px;
      }

      &::after {
        right: -5px;
        top: 55px;
      }

      &-title {
        color: #1b2057;
        font-weight: bold;
        font-size: 22px;
        margin-bottom: 18px;
      }

      &-comma {
        margin-left: -20px;
      }

      &-content {
        position: relative;
        font-size: 14px;
        text-align: left;
        color: #333333;
        line-height: 20px;
        z-index: 2;
      }

      &-pic {
        position: absolute;
        right: 0;
        bottom: 0;
      }
    }

    .report-card {
      background-color: #ffffff;
      border-radius: 8px;
      padding: 16px 10px;
      margin-bottom: 8px;

      &-title {
        font-size: 16px;
        font-weight: 700;
        text-align: left;
        color: #333333;
        margin-bottom: 8px;
        position: relative;

        .text {
          position: relative;
          z-index: 2;
          font-size: 16px;
        }

        &::before {
          content: ""; // 必须要有内容，即使为空字符串
          position: absolute;
          left: -1px;
          top: -3px;
          z-index: 1;
          //   transform: translateY(-50%);
          width: 16px; // 图片的宽度
          height: 16px; // 图片的高度
          background-image: url(""); // 图片路径
          background-repeat: no-repeat;
          background-position: center;
          background-size: cover;
        }
      }

      .row {
        display: flex;
        margin-bottom: 12px;
        font-size: 14px;

        .title {
          white-space: nowrap;
          color: #999999;
          // flex: 0 0 70px;
          min-width: 70px;
          text-align: left;
        }

        .content {
          word-break: break-all;
          flex: 1;
          width: 0;
          color: #333333;
        }
      }

      .column {
        display: flex;
        flex-direction: column;

        // margin-bottom: 24px;
        .title {
          color: #999999;
          margin-bottom: 8px;
        }

        .content {
          word-break: break-all;
          .report-img {
            width: 100%;
            margin-bottom: 8px;
            height: auto;
            object-fit: cover;
          }

          //   &>.report-img:nth-last-of-type(1){
          //     margin-bottom: 0;
          //   }
        }
      }

      & > .row:nth-last-child(1),
      & > .column:nth-last-child(1) {
        margin-bottom: 0;
      }

      .part-card {
        &-title {
          display: flex;
          margin-bottom: 10px;
          margin-top: 18px;

          .serial-num {
            margin-right: 8px;
          }
          & > .content {
            word-break: break-all;
            width: 0;
            flex: 1;
          }
        }

        &-content {
          background-color: #f3f6f8;
          border-radius: 8px;
          padding: 0 10px;

          & > .row {
            padding: 10px 0;
            margin-bottom: 0;
            border-bottom: 1px dashed #cccccc;

            .title {
              white-space: nowrap;
              min-width: 46px;
              // flex: 0 0 46px;
              padding-right: 10px;
              box-sizing: border-box;
              text-align: left;
            }
          }

          & > .row:nth-last-child(1) {
            border-bottom: none;
          }
        }
      }
    }
  }

  &-info {
    color: #999999;
    font-size: 12px;
    line-height: 17px;
    text-align: left;
    width: 100%;
    padding: 8px 10px;
  }

  &-footer {
    width: 100%;
    height: 50px;

    .btn-box {
      height: 50px;
      width: 100%;
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 3;
      padding: 8px;
      box-sizing: border-box;
      background-color: #ffffff;

      .btn {
        width: 100%;
        height: 100%;
        background-color: #0091ff;
        border-radius: 4px;
        color: #ffffff;
        font-size: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;

        &-disabled {
          background-color: #cccccc;
          color: #ffffff;
        }
      }
    }
  }
}

.icon-close {
  display: inline-block;
  width: 12px; // 可以根据需要调整大小
  height: 12px;
  position: relative;
  cursor: pointer;
  color: #333;

  &::before,
  &::after {
    content: "";
    position: absolute;
    left: 50%;
    top: 50%;
    background-color: currentColor;
    width: 1px;
    height: 100%; // 可以根据需要调整比例
    transform-origin: center;
    transition: transform 0.2s ease-in-out;
  }

  &::before {
    transform: translate(-50%, -50%) rotate(45deg);
  }

  &::after {
    transform: translate(-50%, -50%) rotate(-45deg);
  }

  &:hover &::before,
  &:hover &::after {
    transform: translate(-50%, -50%) scale(1.2) rotate(45deg);
  }
}

image {
  height: auto;
}

.serial-num {
  width: 20px;
  min-width: 20px;
  // line-height: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  background: #dcf0ff;
  border-radius: 2px;
  font-size: 12px;
  color: #0091ff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.textarea-box {
  border: 1px solid #e9e9e9;
  padding: 10px;

  background-color: #ffffff;

  .length {
    text-align: right;
    // padding-bottom: 20px;
    color: #999999;
  }
}

.select-box {
  display: flex;
  flex-wrap: wrap;

  .select {
    flex: 0 0 calc(33.333% - 5px);
    width: 0;
    border: 1px solid #cccccc;
    padding: 2px 10px;
    box-sizing: border-box;
    color: #666666;
    margin-right: 5px;
    margin-bottom: 10px;
    border-radius: 4px;
    text-align: center;
    white-space: nowrap;
  }

  .selected {
    border-color: #0091ff;
    color: #0091ff;
  }
}

/deep/.img-upload-btn {
  background-color: #ffffff !important;
}
</style>